<template>
  <div class="system-user-dialog-container">
    <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="1000px">
      <el-form ref="bannerDialogFormRef" :model="state.ruleForm" :rules="rules" size="default" label-width="auto">

        <el-row :gutter="35">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="轮播图" prop="bannerUrl">
              <el-input type="hidden" v-model="state.ruleForm.bannerUrl" placeholder="请输入" clearable></el-input>
              <el-upload
                  v-model:file-list="fileList"
                  list-type="picture-card"
                  action="https://www.slkjyun.cn/api/admin/file/upload"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
              >
                <el-icon>
                  <Plus/>
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="35">
          <el-col :span="24" class="mb20">
            <el-form-item label="所属机构" prop="orgId">
              <el-tree-select
                  v-model="state.ruleForm.orgId"
                  :data="props.orgTree??[]"
                  :render-after-expand="false"
                  style="width: 500px"
                  check-strictly
                  filterable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="35">
          <el-col :span="24" class="mb20">
            <el-form-item label="轮播图标题" prop="bannerTitle">
              <el-input v-model="state.ruleForm.bannerTitle"
                        placeholder="请输入轮播图标题"
                        clearable>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="35">
          <el-col :span="24" class="mb20">
            <el-form-item label="轮播优先级" prop="bannerPriority">
              <el-input-number v-model="state.ruleForm.bannerPriority" :min="1"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="35">
          <el-col :span="24" class="mb20">
            <el-form-item label="轮播图跳转链接" prop="linkUrl">
              <el-input v-model="state.ruleForm.linkUrl" placeholder="请输入轮播图跳转链接" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(bannerDialogFormRef)" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogVisible">
      <img w-full h-full style="width: 100%;height: 100%" :src="dialogImageUrl" alt="Preview Image"/>
    </el-dialog>

  </div>
</template>

<script setup lang="ts" name="BannerDialog">
import {nextTick, reactive, ref} from 'vue';
import {systemApi} from "/@/api/system";
import type {UploadProps, UploadUserFile} from 'element-plus'
import {ElMessage, FormInstance, FormRules} from "element-plus";
import {useBannerApi} from "/@/api/cms/banner";
import {Plus} from "@element-plus/icons-vue";

const {add, edit} = useBannerApi();

const {orgTree} = systemApi();
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
// 定义属性，父传子
const props = defineProps(['orgId', 'orgTree', 'channelTree']);
// 定义变量内容
const bannerDialogFormRef = ref();
const state = reactive({
  sysOrgData: [] as OrgTreeType[],
  ruleForm: {
    id: '',
    orgId: '',
    bannerUrl: '',
    bannerTitle: '',
    bannerPriority: '',
    bannerDisable: '',
    tenantId: '',
    isDelete: '',
    linkUrl: ''
  },
  editor: {
    htmlVal: '',
    textVal: '',
    disable: false,
  },
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: '',
  },
  sysOrgTreeData: {
    data: [],
    total: 0,
    loading: false,
    param: {
      pageNum: 1,
      pageSize: 2100,
    },
  }
});

const rules = reactive<FormRules<any>>({
  orgId: [
    {required: true, message: '请选择栏目区域', trigger: 'change'},
  ],
  bannerUrl: [
    {required: true, message: '请上传幻灯片图片不能为空', trigger: 'blur'},
  ],
  bannerTitle: [
    {required: true, message: '幻灯片标题不能为空', trigger: 'blur'},
    {min: 3, max: 40, message: '幻灯片标题长度应该在3到40个字符之间', trigger: 'blur'},
  ],
  bannerPriority: [
    {required: true, message: '栏目序号不能为空'},
    {type: 'number', message: '栏目序号必须为数字'},
  ]
})

// 打开弹窗
const openDialog = async (type: string, row: RowCmsBannerType) => {
  state.ruleForm.orgId = props.orgId;
  if (type === 'edit') {
    state.dialog.title = '修改轮播图';
    state.ruleForm = row;
    fileList.value = [];
    fileList.value.push({name: row.bannerUrl, url: row.bannerUrl})
    console.log('update', state.ruleForm)
  } else {
    state.dialog.title = '新建录播图';
    state.ruleForm.bannerTitle = '';
    fileList.value = [];
    clearForm();
    console.log('new', state.ruleForm)
    // await nextTick(() => {
    //   if (bannerDialogFormRef.value) {
    //     bannerDialogFormRef.value.resetFields();
    //   }
    // });
  }
  state.dialog.submitTxt = '保存并发布';
  state.dialog.isShowDialog = true;
};
// 关闭弹窗
const closeDialog = async () => {
  state.dialog.isShowDialog = false;
  await nextTick(() => {
    if (bannerDialogFormRef.value) {
      console.log('bannerDialogFormRef', bannerDialogFormRef.value)
      bannerDialogFormRef.value.resetFields();
    }
  });
};
// 取消
const onCancel = () => {
  closeDialog();
};
// 提交
const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (!valid) {
      console.log('error submit!!', fields);
      ElMessage.error('数据校验失败!');
      return false;
    }
    state.ruleForm.orgId = props.orgId;
    const res = state.ruleForm.id ? await edit(state.ruleForm) : await add(state.ruleForm)
    if (res.status === 200) {
      await nextTick(() => {
        if (bannerDialogFormRef.value) {
          console.log('bannerDialogFormRef', bannerDialogFormRef.value)
          bannerDialogFormRef.value.resetFields();
        }
      });
      ElMessage.success(state.ruleForm.id ? '保存成功' : '保存成功');
    }
    closeDialog();
    emit('refresh');
    // if (state.dialog.type === 'add') { }
  });
};

const clearForm = () => {
  state.ruleForm.id = '';
  state.ruleForm.orgId = '';
  state.ruleForm.bannerUrl = '';
  state.ruleForm.bannerTitle = '';
  state.ruleForm.bannerPriority = '';
  state.ruleForm.bannerDisable = '';
  state.ruleForm.tenantId = '';
  state.ruleForm.isDelete = '';
  state.ruleForm.linkUrl = '';
  state.ruleForm = {
    id: '',
    orgId: '',
    bannerUrl: '',
    bannerTitle: '',
    bannerPriority: '',
    bannerDisable: '',
    tenantId: '',
    isDelete: '',
    linkUrl: ''
  }
}

const fileList = ref<UploadUserFile[]>([])

const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  state.ruleForm.bannerUrl = response.data
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {

  if (fileList.value.length === 1) {
    ElMessage.error('只能上传一张图片!')
    return false
  }

  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('必须为png或jpeg格式的图片!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
}

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

// 暴露变量
defineExpose({
  openDialog,
});
</script>
<style scoped lang="scss">
.croppers-container {
  .cropper-img-warp {
    text-align: center;

    .cropper-img {
      margin: auto;
      width: 150px;
      height: 150px;
      border-radius: 100%;
    }
  }
}
</style>
